package com.quectel.core.module.partybuildingtask.service.impl;


import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.func.LambdaUtil;
import com.quectel.constant.core.partybuilding.PartyBuildingPlanConstants;
import com.quectel.constant.global.SystemConstants;
import com.quectel.util.aspect.lock.annotation.Lock;
import com.quectel.core.constants.RedisCacheConstants;
import com.quectel.core.constants.RedisLockConstants;
import com.quectel.core.module.partybuilding.dto.PartyOrganizationDto;
import com.quectel.core.module.partybuilding.dto.PartyPersonDto;
import com.quectel.core.module.partybuilding.service.PartyOrganizationService;
import com.quectel.core.module.partybuilding.service.PartyPersonService;
import com.quectel.core.module.partybuildingtask.dao.PartyBuildingPlanTaskDao;
import com.quectel.core.module.partybuildingtask.dto.PartyBuildingPlanDto;
import com.quectel.core.module.partybuildingtask.dto.PartyBuildingPlanPersonBindingDto;
import com.quectel.core.module.partybuildingtask.dto.PartyBuildingPlanTaskDto;
import com.quectel.core.module.partybuildingtask.entity.PartyBuildingPlanTaskEntity;
import com.quectel.core.module.partybuildingtask.service.PartyBuildingPlanPersonBindingService;
import com.quectel.core.module.partybuildingtask.service.PartyBuildingPlanService;
import com.quectel.core.module.partybuildingtask.service.PartyBuildingPlanTaskService;
import com.quectel.util.common.CopyUtils;
import com.quectel.util.common.DateUtils;
import com.quectel.util.common.JacksonUtils;
import com.quectel.util.kit.CacheKit;
import com.quectel.util.kit.Snowflake;
import com.quectel.util.mybatis.MyBatisPlusUtils;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Consumer;
import java.util.function.Function;

/**
 * @author bob
 * @email bob.yu@quectel.com
 * @date 2023/05/24 11:32
 */
@DubboService
public class PartyBuildingPlanTaskServiceImpl implements PartyBuildingPlanTaskService {

    private static final Logger LOGGER = LoggerFactory.getLogger(PartyBuildingPlanTaskServiceImpl.class);

    /**
     * 入参解释:实体id
     */
    private static final Function<Long, String> PARTY_BUILDING_PLAN_TASK_CACHE_BY_ID_FUNC = id -> String.format(RedisCacheConstants.PROJECT_NAME + "PARTY_BUILDING_PLAN_TASK_CACHE_BY_ID:%d", id);

    /**
     * 清除缓存方法
     */
    private static final Consumer<PartyBuildingPlanTaskDto> CLEAR_CACHE_FUNC = dto -> {
        CacheKit.invalidRedisCache(PARTY_BUILDING_PLAN_TASK_CACHE_BY_ID_FUNC.apply(dto.getId()));
    };

    @Autowired
    private PartyBuildingPlanTaskDao partyBuildingPlanTaskDao;
    @Autowired
    private PartyBuildingPlanService partyBuildingPlanService;
    @Autowired
    private PartyOrganizationService partyOrganizationService;
    @Autowired
    private PartyPersonService partyPersonService;
    @Autowired
    private PartyBuildingPlanPersonBindingService partyBuildingPlanPersonBindingService;

    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    @Lock(
            lockExpresses = {
                    RedisLockConstants.PARTY_BUILDING_PLAN_LOCK + "#{#planDto.id}"
            }
    )
    public void genTask(PartyBuildingPlanDto planDto, Date date) {
        //查询参与人员
        List<PartyBuildingPlanPersonBindingDto> persons = partyBuildingPlanPersonBindingService.selectByPlanId(planDto.getId());
        if(CollectionUtils.isEmpty(persons)){
            return;
        }
        //任务开始时间
        for (PartyBuildingPlanPersonBindingDto person : persons) {

            //任务提醒时间
            PartyPersonDto partyPersonDto = partyPersonService.selectCacheById(person.getPersonId());
            if(partyPersonDto==null){
                continue;
            }
            //查询是否生成,如果已经生成则跳过
            Map<String,Object> params = new HashMap<>();
            params.put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getTenantId),planDto.getTenantId());
            params.put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getPartyId),planDto.getPartyId());
            params.put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getPlanId),planDto.getId());
            params.put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getDate),DateUtils.format(date, DateUtils.FormatType.SIMPLE));
            params.put(LambdaUtil.getFieldName(PartyBuildingPlanTaskDto::getExecUserId),partyPersonDto.getId());
            if(queryTotal(params)>0){
                continue;
            }

            PartyBuildingPlanTaskDto partyBuildingPlanTaskDto = new PartyBuildingPlanTaskDto();
            partyBuildingPlanTaskDto.setTenantId(planDto.getTenantId());
            partyBuildingPlanTaskDto.setPartyId(planDto.getPartyId());
            partyBuildingPlanTaskDto.setPlanId(planDto.getId());
            partyBuildingPlanTaskDto.setPlanSnapshot(JacksonUtils.toJsonString(planDto));
            partyBuildingPlanTaskDto.setName(DateUtils.format(date, DateUtils.FormatType.SIMPLE) + planDto.getName());
            partyBuildingPlanTaskDto.setExecUserId(person.getPersonId());
            partyBuildingPlanTaskDto.setExecUsername(partyPersonDto.getName());
            partyBuildingPlanTaskDto.setDate(date);
            partyBuildingPlanTaskDto.setExecStatus(PartyBuildingPlanConstants.TaskStatus.UNCOMPLETED.getStatus());
            partyBuildingPlanTaskDto.setCreateTime(new Date());

            if(PartyBuildingPlanConstants.RemindType.NOT_REMIND.getType().equals(planDto.getRemindType())){
                partyBuildingPlanTaskDto.setIsPush(SystemConstants.YES);
                partyBuildingPlanTaskDto.setRemindTime(date);
            }else {
                //计算提醒日期
                DateTime dateTime = DateUtil.beginOfDay(date);
                PartyBuildingPlanConstants.RemindType byType = PartyBuildingPlanConstants.RemindType.getByType(planDto.getRemindType());
                if(byType==null){
                    continue;
                }
                DateTime remindTime = DateUtil.offsetHour(dateTime, byType.getHour());
                partyBuildingPlanTaskDto.setRemindTime(remindTime);
                partyBuildingPlanTaskDto.setIsPush(SystemConstants.NO);
            }
            save(partyBuildingPlanTaskDto);
        }
    }

    @Override
    public PartyBuildingPlanTaskDto selectCacheById(Long id) {
        return CacheKit.cacheToRedis(
                () -> selectById(id),
                PARTY_BUILDING_PLAN_TASK_CACHE_BY_ID_FUNC.apply(id),
                SystemConstants.NOT_NULL_CACHE_EXPIRE_SECONDS
        );
    }

    @Override
    public PartyBuildingPlanTaskDto selectById(Long id) {
        PartyBuildingPlanTaskEntity entity = partyBuildingPlanTaskDao.selectById(id);
        return paddingField(CopyUtils.copyObj(entity, PartyBuildingPlanTaskDto.class));
    }

    @Override
    public List<PartyBuildingPlanTaskDto> queryList(Map<String, Object> params) {
        List<PartyBuildingPlanTaskEntity> list = partyBuildingPlanTaskDao.queryList(params);
        List<PartyBuildingPlanTaskDto> result = CopyUtils.copyList(list, PartyBuildingPlanTaskDto.class);
        result.forEach(this::paddingField);
        return result;
    }

    /**
     * 此方法慎用 禁止填充List一类 比如一个人有多个地址这里不允许填充
     * 填充的原则是: 1:被填充对象不经常变换 2:根据id可以走缓存 3数据足够简单 比如设备类型 所属园区等
     *
     * @param dto
     * @return
     */
    private PartyBuildingPlanTaskDto paddingField(PartyBuildingPlanTaskDto dto) {
        if (dto != null) {

            PartyPersonDto partyPersonDto = partyPersonService.selectCacheById(dto.getExecUserId());
            if(partyPersonDto!=null){
                PartyOrganizationDto partyOrganizationDto = partyOrganizationService.selectCacheById(partyPersonDto.getPartyId());
                if(partyOrganizationDto!=null){
                    dto.setPartyName(partyOrganizationDto.getName());
                }
            }

            PartyBuildingPlanDto partyBuildingPlanDto = JacksonUtils.parse(dto.getPlanSnapshot(), PartyBuildingPlanDto.class);
            if(partyBuildingPlanDto!=null){
                dto.setPlanName(partyBuildingPlanDto.getName());
                dto.setPlanStartTime(DateUtils.format(partyBuildingPlanDto.getStartTime(), DateUtils.FormatType.COMMON));
                String endTime = DateUtils.format(partyBuildingPlanDto.getEndTime(), DateUtils.FormatType.COMMON);
                if(PartyBuildingPlanConstants.LONG_TERM_TIME.equals(endTime)){
                    dto.setPlanEndTime(PartyBuildingPlanConstants.LONG_TERM_DESC);
                }else{
                    dto.setPlanEndTime(DateUtils.format(partyBuildingPlanDto.getEndTime(), DateUtils.FormatType.COMMON));
                }
                dto.setPlanPeriodValue(partyBuildingPlanDto.getPeriodValue());
            }

            //任务状态 1未开始 2进行中 3已结束 4已取消
            if(PartyBuildingPlanConstants.TaskStatus.CANCELED.getStatus().equals(dto.getExecStatus())){
                dto.setStatus(PartyBuildingPlanConstants.PlanStatus.CANCELED.getStatus());
            }else if(DateTime.now().before(DateUtil.beginOfDay(dto.getDate())) || (partyBuildingPlanDto!=null && DateTime.now().before(partyBuildingPlanDto.getStartTime()))){
                dto.setStatus(PartyBuildingPlanConstants.PlanStatus.NOT_BEGIN.getStatus());
            }else if(DateTime.now().after(DateUtil.endOfDay(dto.getDate())) || (partyBuildingPlanDto!=null && DateTime.now().after(partyBuildingPlanDto.getEndTime()))){
                dto.setStatus(PartyBuildingPlanConstants.PlanStatus.ENDED.getStatus());
            }else {
                dto.setStatus(PartyBuildingPlanConstants.PlanStatus.IN_PROGRESS.getStatus());
            }

            dto.setPlanSnapshot(null);

        }
        return dto;
    }

    @Override
    public int queryTotal(Map<String, Object> params) {
        return partyBuildingPlanTaskDao.queryTotal(params);
    }

    @Override
    public Long save(PartyBuildingPlanTaskDto dto) {
        PartyBuildingPlanTaskEntity entity = CopyUtils.copyObj(dto, PartyBuildingPlanTaskEntity.class);
        entity.setId(Snowflake.nextId());
        partyBuildingPlanTaskDao.insert(entity);
        return entity.getId();
    }

    @Override
    @Lock(
            lockExpresses = {
                    RedisLockConstants.PARTY_BUILDING_PLAN_TASK_LOCK + "#{#dto.id}"
            }
    )
    public void updateById(PartyBuildingPlanTaskDto dto) {
        PartyBuildingPlanTaskEntity entity = CopyUtils.copyObj(dto, PartyBuildingPlanTaskEntity.class);

        partyBuildingPlanTaskDao.updateById(entity);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    @Lock(
            lockExpresses = {
                    RedisLockConstants.PARTY_BUILDING_PLAN_TASK_LOCK + "#{#dto.id}"
            }
    )
    public void updateAllColumnById(PartyBuildingPlanTaskDto dto) {
        PartyBuildingPlanTaskEntity entity = CopyUtils.copyObj(dto, PartyBuildingPlanTaskEntity.class);

        MyBatisPlusUtils.updateAllColumnById(entity, partyBuildingPlanTaskDao);

        CLEAR_CACHE_FUNC.accept(dto);
    }

    @Override
    public void deleteById(Long id) {

        CLEAR_CACHE_FUNC.accept(selectById(id));

        partyBuildingPlanTaskDao.deleteById(id);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(Long[] ids) {
        for (Long id : ids) {
            deleteById(id);
        }
    }
}
